local rewrite_conf = require("config.rewrite");
local string_utils = require("mvc.utils.string_utils");
local const = require("mvc.config.const");

local rewrite_handler = {};

--[[
	根据uri获取对应的urlrewrite配置对应的新的转发地址
	{
		from = "^/at/(%w+).html",
		to   = "/newatt/view?urlStr={1}"
	}
	根据请求地址：http://xxx.xxx.com/at/ab123.html
	返回目标地址：/newatt/view?urlStr=ab123
]]
function rewrite_handler.get_target(uri)
	
	assert(rewrite_conf, "config/rewrite.lua configuration file deficiency")

	local ri = nil;
	for i = 1, #rewrite_conf, 1 do
		ri = rewrite_conf[i];
		local from = ri.from;
		local to = ri.to;
		assert(from, "from不能为nil");
		assert(to, "to不能为nil");
		local match_uri_param = string_utils.match_regx(uri, from)
		if match_uri_param ~= nil then
			return rewrite_handler.new_uri_and_req_params(to, match_uri_param);
		end
	end
	
	return nil;
end

--[[
	将to中的变量替换为匹配返回值
]]
function rewrite_handler.new_uri_and_req_params(to, match_uri_param)
	local b = string.find(to, "?");
	local e = #to;
	if b ~= nil then
		e = b - 1;
	end
	
	for i = 1, #match_uri_param, 1 do
		to = string.gsub(to, "{" .. i .. "}", match_uri_param[i]);
	end
	rewrite_handler.params_forward(string.sub(to, b + 1, #to));
	to = string.sub(to, 1, e);
	return to;
end

--[[
	参数内部重定向
]]
function rewrite_handler.params_forward(to)
	local fp = {};
	if string_utils.is_blank(to) then
		return;
	end
	
	local arr = string_utils.split(to, "&");
	local ta = {};
	for i = 1, #arr, 1 do
		ta = string_utils.split(arr[i], "=");
		if #ta > 1 then
			fp[ta[1]] = ta[2];
			ngx.ctx[const.ISR] = true;
		end
	end
	ngx.ctx[const.FOP] = fp;
end

return rewrite_handler;
